package com.yj.suncity.user;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.bean.LoginBean;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.HttpUtil;
import com.yj.suncity.utis.ProgressUtil;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.UploadUtil;
import com.yj.suncity.utis.DialogUtils.ItemCall;
import com.yj.suncity.utis.UploadUtil.OnUploadProcessListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class UpdateUserInfoActivity extends Activity implements OnClickListener {
	private final int PIC_FROM_CAMERA = 101;
	private final int PIC_FROM＿LOCALPHOTO = 102;
	private static final int FAIL = 1;
	private static final int SUCCESS = 2;
	private static final int IO_EXCEPTION = 3;
	private static final int JSON_EXCEPTION = 4;
	private Context context;
	private String userId;
	private ImageView mImg_user_logo;
	private String uploadHead = "";
	private String user_head_img = "";
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private List<NameValuePair> pairs = new ArrayList<NameValuePair>();
	private TextView mTxt_sex;
	private String sex;
	private String sexId;
	private EditText mEdt_username, mEdt_realname, mEdt_id_card,
			mEdt_user_email;
	private ProgressUtil progressUtil;
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, (String) msg.obj);
				break;
			case SUCCESS:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, "修改成功！");
				UpdateUserInfoActivity.this.finish();
				break;
			case IO_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, "网络异常！");
				break;
			case JSON_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, "数据解析异常！");
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_user_info);
		context = this;
		userId = getIntent().getStringExtra("userid");
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
		initData();
	}

	private void initData() {
		String path = URLCon.用户 + "?action=getmemberinfo&id=" + userId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在加载......",
				new AsyncTaskUtil.ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						LoginBean bean = new LoginBean(jsonObject);
						sexId = bean.getSex();
						if (bean.getSex().equals("0")) {
							sex = "男";
							mTxt_sex.setText(sex);
						} else {
							sex = "女";
							mTxt_sex.setText(sex);
						}
						user_head_img = bean.getHead_photo();
						imageLoader.displayImage(URLCon.HOST + user_head_img,
								mImg_user_logo, options);

						mEdt_username.setText(bean.getUsername());
						mEdt_realname.setText(bean.getRealname());
						mEdt_id_card.setText(bean.getId_card());
						mEdt_user_email.setText(bean.getEmail());

					}
				});
		asyncTaskUtil.execute(path);
	}

	private void findView() {
		mImg_user_logo = (ImageView) findViewById(R.id.img_user_logo);
		mImg_user_logo.setOnClickListener(this);
		mTxt_sex = (TextView) findViewById(R.id.txt_user_sex);
		mTxt_sex.setOnClickListener(this);

		mEdt_username = (EditText) findViewById(R.id.edt_username);
		mEdt_realname = (EditText) findViewById(R.id.edt_realname);
		mEdt_id_card = (EditText) findViewById(R.id.edt_id_card);
		mEdt_user_email = (EditText) findViewById(R.id.edt_user_email);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.img_user_logo:
			popPhotoView();
			break;
		case R.id.txt_user_sex:
			popSexView();
			break;
		case R.id.btn_ok:
			// 修改
			progressUtil = new ProgressUtil();
			if (uploadHead.equals("")) {
				uploadHead = user_head_img;
				if (!setPairs())
					return;
				progressUtil.ShowProgress(context, true, false, "正在修改......");
				updateInfo();
				return;
			} else {
				if (!setPairs())
					return;
				progressUtil.ShowProgress(context, true, false, "正在修改......");
				Log.d("", "uploadHead==" + uploadHead);
				Map<String, String> param = new LinkedHashMap<String, String>();
				List<String> filePaths = new ArrayList<String>();
				filePaths.add(uploadHead);
				param.put("action", "uploads");

				UploadUtil uploadUtil = new UploadUtil();
				uploadUtil.uploadFile(context, filePaths, "txtimg",
						URLCon.图片上传, param, new OnUploadProcessListener() {
							@Override
							public void UploadResule(String result) {
								Log.d("", "result===" + result);
								// {"success":"1","msg":"ä¸ä¼ æå","data":[{"url":
								// "/upload/201504/15/201504151021483780.jpg"}]}

								try {
									JSONObject jsonObject = new JSONObject(
											result);
									if (jsonObject.optString("success").equals(
											"1")) {
										JSONArray array = jsonObject
												.optJSONArray("data");
										JSONObject item = array
												.optJSONObject(0);
										uploadHead = item.optString("url");
										preferencesUtil.putString(context,
												ShareCon.USERFILE,
												ShareCon.USERLOGO, uploadHead);
										updateInfo();
									} else {
										Message message = new Message();
										message.what = FAIL;
										message.obj = jsonObject
												.optString("msg");
										handler.sendMessage(message);
									}
								} catch (JSONException e) {
									Message message = new Message();
									message.what = JSON_EXCEPTION;
									handler.sendMessage(message);
									e.printStackTrace();
								}
							}
						});
			}
			break;
		default:
			break;
		}
	}

	private boolean setPairs() {
		pairs.clear();
		String userName = mEdt_username.getText().toString().trim();
		String realName = mEdt_realname.getText().toString().trim();
		String userIdCard = mEdt_id_card.getText().toString().trim();
		String userEmail = mEdt_user_email.getText().toString().trim();
		if (userName.equals("")) {
			ToastUtil.ShowToast(context, "请输入用户名！");
			return false;
		}
		if (realName.equals("")) {
			ToastUtil.ShowToast(context, "请输入真实姓名！");
			return false;
		}
		if (userIdCard.equals("")) {
			ToastUtil.ShowToast(context, "请输入身份证号！");
			return false;
		}
		if (userEmail.equals("")) {
			ToastUtil.ShowToast(context, "请输入电子邮箱！");
			return false;
		}

		pairs.add(new BasicNameValuePair("action", "modify"));
		pairs.add(new BasicNameValuePair("id", userId));
		pairs.add(new BasicNameValuePair("username", userName));
		pairs.add(new BasicNameValuePair("realname", realName));
		pairs.add(new BasicNameValuePair("sex", sexId));
		pairs.add(new BasicNameValuePair("id_card", userIdCard));
		pairs.add(new BasicNameValuePair("email", userEmail));
		pairs.add(new BasicNameValuePair("head_photo", uploadHead));

		pairs.add(new BasicNameValuePair("password", ""));
		pairs.add(new BasicNameValuePair("pay_pwd", ""));
		pairs.add(new BasicNameValuePair("secrecy_problem", ""));
		pairs.add(new BasicNameValuePair("secrecy_answer", ""));
		pairs.add(new BasicNameValuePair("birthday", ""));
		pairs.add(new BasicNameValuePair("address", ""));
		return true;
	}

	private void updateInfo() {
		final String path = URLCon.用户;
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String json = HttpUtil.HttpClientdoPost(path, pairs);
					JSONObject jsonObject = new JSONObject(json);
					if (jsonObject.optString("success").equals("1")) {
						Message message = new Message();
						message.what = SUCCESS;
						handler.sendMessage(message);
					} else {
						Message message = new Message();
						message.what = FAIL;
						message.obj = jsonObject.optString("msg");
						handler.sendMessage(message);
					}
				} catch (IOException e) {
					Message message = new Message();
					message.what = IO_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				} catch (JSONException e) {
					Message message = new Message();
					message.what = JSON_EXCEPTION;
					handler.sendMessage(message);
					e.printStackTrace();
				}

			}
		});
		thread.start();
		thread = null;
	}

	// =============================================================================
	private void popSexView() {
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.SelectSexDialog(context, new ItemCall() {
			@Override
			public void onIndexCall(int index) {
				if (index == 0) {// 男
					sex = "男";
					sexId = "0";
				} else if (index == 1) {// 女
					sex = "女";
					sexId = "1";
				}
				mTxt_sex.setText(sex);
			}
		});
	}

	private void popPhotoView() {
		DialogUtils dialogUtils = DialogUtils.getInstance();
		dialogUtils.SelectPicDialog(context, new ItemCall() {
			@Override
			public void onIndexCall(int index) {
				if (index == 0) {
					doHandlerPhoto(PIC_FROM_CAMERA);
				} else {
					doHandlerPhoto(PIC_FROM＿LOCALPHOTO);
				}
			}
		});
	}

	/**
	 * 根据不同方式选择图片设置ImageView
	 * 
	 * @param type
	 *            0-本地相册选择，非0为拍照
	 */
	private Uri photoUri;// 需要上传的头像

	private void doHandlerPhoto(int type) {
		try {
			// 保存裁剪后的图片文件
			File pictureFileDir = new File(
					Environment.getExternalStorageDirectory(), "/upload");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			} else {
				File[] files = pictureFileDir.listFiles();
				if (files != null) {
					for (File file : files) {
						file.delete();
					}
				}
			}
			File picFile = new File(pictureFileDir, getPhotoFileName());
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			// photoUri = picFile.toString();
			if (type == PIC_FROM＿LOCALPHOTO) {
				Intent intent = getCropImageIntent();
				startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
			} else {
				Intent cameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(cameraIntent, PIC_FROM_CAMERA);
			}

		} catch (Exception e) {
			Log.i("HandlerPicError", "处理图片出现错误");
		}
	}

	/**
	 * 调用本地图片剪辑程序
	 */
	public Intent getCropImageIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		setIntentParams(intent);
		return intent;
	}

	/**
	 * 启动相机裁剪程序
	 */
	private void cropImageUriByTakePhoto() {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		setIntentParams(intent);
		startActivityForResult(intent, PIC_FROM＿LOCALPHOTO);
	}

	/**
	 * 设置公用参数
	 */
	private void setIntentParams(Intent intent) {
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 600);
		intent.putExtra("outputY", 600);
		intent.putExtra("noFaceDetection", true); // no face detection
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
	}

	/**
	 * 用时间戳生成照片名称
	 * 
	 * @return
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'yyyyMMddHHmmss");
		return dateFormat.format(date) + ".jpg";
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PIC_FROM_CAMERA: // 拍照
			try {
				cropImageUriByTakePhoto();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case PIC_FROM＿LOCALPHOTO:
			try {
				if (photoUri != null) {
					Bitmap bitmap = BitmapFactory.decodeFile(photoUri
							.toString().replace("file://", ""));
					Log.d("", "bitmap=="+bitmap);
                    if (bitmap!=null) {
                    	uploadHead = photoUri.toString().replace("file://", "");
                    	imageLoader.displayImage("file://" + uploadHead,
                    			mImg_user_logo, options);
					}
					
//					uploadHead = photoUri.toString().replace("file://", "");
//					imageLoader.displayImage("file://" + uploadHead,
//							mImg_user_logo, options);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

}
